var fs = require("fs"),
    path = require("path"),
    menusJsonPath = path.join(global.rootPath, "/assets/json/menus.json");

var MenuModel = function(_id, _name, _url, _index, _remark, _pId) {

    this.id = _id;
    this.name = _name || "";
    this.pId = _pId || 'root';
    this.url = _url || "";
    this.index = _index || 0;
    this.date = new Date();
    this.remark = _remark || "";
};

MenuModel.prototype = {

    add: function(_callBack) {

        if (this.select(this.id) != null) {
            return this.edit(this.id, _callBack);
        }
        var menus = global.menus;
        menus.push(this.getAttr());
        saveJson(_callBack);
    },
    del: function(_id, _callBack) {

        var menus = global.menus;
        i = menus.length - 1;
        for (i; i >= 0; i--) {
            if (menus[i].id == _id) break;
        }
        if (i >= 0) {
            menus.splice(i, 1);
            saveJson(_callBack);
        } else {
            _callBack({
                result: false
            });
        }
    },
    edit: function(_id, _callBack) {

        var menus = global.menus;
        i = menus.length - 1;
        for (i; i >= 0; i--) {
            if (menus[i].id == _id) break;
        }
        if (i >= 0) {
            menus[i].name = this.name;
            menus[i].url = this.url;
            menus[i].index = this.index;
            menus[i].remark = this.remark;
            saveJson(_callBack);
        } else {
            _callBack({
                result: false
            });
        }
    },
    select: function(_id) {

        var menus = global.menus,
            i = menus.length - 1;
        for (i; i >= 0; i--) {
            if (menus[i].id == _id) break;
        };
        return i >= 0 ? menus[i] : null;
    },
    getAttr: function() {

        return {
            id: this.id,
            name: this.name,
            pId: this.pId,
            url: this.url,
            index:this.index,
            createDate: this.date.format("yyyy-MM-dd hh:mm"),
            remark: this.remark
        };
    }
};

function saveJson(_callBack) {

    fs.writeFile(menusJsonPath, JSON.stringify(global.menus, null, "\t"), function(err) {
        if (err) {
            console.log(err);
            if (_callBack) _callBack({
                result: false
            });
        }
        if (_callBack)
            _callBack({
                result: true
            });
    });
};

module.exports = MenuModel;